import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'package:ball_lion/module/pick/information/information_logic.dart';
import 'package:ball_lion/module/pick/information/information_item.dart';
import 'package:ball_lion/module/pick/items/banner_scaffold.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/date_time_utils.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';

class SecretListPage extends StatefulWidget {
  const SecretListPage({super.key, this.showAppBar = true});

  final bool showAppBar;

  @override
  State<SecretListPage> createState() => _SecretListPageState();
}

class _SecretListPageState extends State<SecretListPage> {
  late final SecretLogic logic;

  @override
  void initState() {
    logic = Get.put(SecretLogic(), tag: "${widget.showAppBar}");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SecretLogic>(
        tag: "${widget.showAppBar}",
        builder: (logic) {
          return VisibilityDetector(
            key: const Key("secret"),
            onVisibilityChanged: (VisibilityInfo info) {
              if (!info.visibleBounds.isEmpty && logic.secrets[0] != null) {
                logic.getRefresh();
              }
            },
            child: Scaffold(
              appBar: widget.showAppBar
                  ? Styles.appBar(title: const QsText("海外情报"))
                  : null,
              body: Container(
                decoration: const BoxDecoration(
                    gradient: LinearGradient(
                        colors: [Colours.white, Colours.greyF2F3F7],
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        stops: [0, 0.6])),
                child: BannerScaffold(
                    type: "secret${widget.showAppBar ? "" : "_home"}",
                    needScroll: true,
                    needAppBar: false,
                    backFade: widget.showAppBar,
                    cornerFade: widget.showAppBar,
                    fadeColor: widget.showAppBar ? Colours.greyF2F3F7 : null,
                    bannerHeight:
                        Get.width * (widget.showAppBar ? 164 : 120) / 359,
                    picPadding: widget.showAppBar
                        ? null
                        : const EdgeInsets.symmetric(horizontal: 8),
                    picDecoration: widget.showAppBar
                        ? null
                        : BoxDecoration(borderRadius: BorderRadius.circular(8)),
                    backColor: widget.showAppBar ? null : Colours.greyF2F3F7,
                    picOverLay: widget.showAppBar ? 12 : 0,
                    refreshController: logic.refreshController,
                    scrollController: logic.refreshScroll,
                    onRefresh: logic.getRefresh,
                    onLoad: logic.loadMore,
                    body: (physics) => Column(
                          children: [
                            Container(
                              color: widget.showAppBar || logic.showTabColor
                                  ? Colours.white
                                  : Colours.transparent,
                              child: Row(
                                children: [
                                  Expanded(
                                    child: SizedBox(
                                      height: 40,
                                      child: Styles.tabbar(
                                          scrollable: true,
                                          labelPadding:
                                              const EdgeInsets.symmetric(
                                                  horizontal: 12),
                                          controller: logic.tabController,
                                          tabs: logic.tabs
                                              .map((e) => QsText(e))
                                              .toList(),
                                          onTap: (value) => Utils.onEvent(
                                              "jmnc",
                                              params: {"jmnc": value})),
                                    ),
                                  ),
                                  QsText("共计${logic.total[logic.index]}条",
                                          fontSize: 12, color: Colours.grey66)
                                      .paddingOnly(right: 16)
                                ],
                              ),
                            ),
                            Expanded(
                              child: Stack(
                                children: [
                                  ExtendedTabBarView(
                                      controller: logic.tabController,
                                      children: List.generate(
                                          logic.secrets.length,
                                          (index) => LoadingWidget<bool>(
                                                isLoading:
                                                    logic.secrets[index] ==
                                                        null,
                                                data: logic.secrets[index]
                                                        ?.length ==
                                                    0,
                                                noData: NoDataWidget(
                                                    needScroll: true,
                                                    physics: physics),
                                                child: () => ListView(
                                                    physics: physics,
                                                    children: [
                                                      const HeaderLocator(
                                                          clearExtent: false),
                                                      ...List.generate(
                                                          logic.secrets[index]
                                                                  ?.length ??
                                                              0, (i) {
                                                        var e = logic
                                                            .secrets[index]![i];
                                                        if (DateTime.parse(
                                                                e.matchTime!)
                                                            .add(const Duration(
                                                                hours: 2))
                                                            .isBefore(DateTime
                                                                .now())) {
                                                          logic.findHistory ??=
                                                              i;
                                                        }
                                                        return SecretItem(
                                                          secret: e,
                                                          showHistory: i ==
                                                                  logic
                                                                      .findHistory &&
                                                              index == 0,
                                                          margin: EdgeInsets
                                                              .fromLTRB(
                                                                  8,
                                                                  i == 0 &&
                                                                          !widget
                                                                              .showAppBar
                                                                      ? 3
                                                                      : 8,
                                                                  8,
                                                                  0),
                                                          onChange: (change) {
                                                            if (change == true)
                                                              logic
                                                                  .getRefresh();
                                                          },
                                                        );
                                                      }),
                                                      const FooterLocator()
                                                    ]),
                                              ))),
                                  Positioned(
                                    bottom: 0,
                                    left: 0,
                                    right: 0,
                                    child: _buyBottom(),
                                  )
                                ],
                              ),
                            )
                          ],
                        )),
              ),
            ),
          );
        });
  }

  Widget _buyBottom() {
    return Padding(
      padding: EdgeInsets.fromLTRB(
          12, 0, 12, 24 + MediaQuery.of(context).padding.bottom),
      child: Stack(
        children: [
          Container(
            height: 48,
            alignment: Alignment.center,
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(
                color: Colours.white,
                borderRadius: BorderRadius.circular(24),
                boxShadow: [
                  BoxShadow(
                      color: const Color(0xFF87909D).withOpacity(0.13),
                      blurRadius: 12,
                      offset: const Offset(0, 4))
                ]),
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.only(left: 16, right: 4),
                  height: 48,
                  child: Row(
                    children: [
                      if (logic.price?.length != 0)
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                QsText(
                                  "${logic.realPrice ?? ""}球币".changeUnit,
                                  color: Colours.main,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                  height: 1.4,
                                ),
                                if (logic.price != logic.realPrice)
                                  QsText(
                                    "${logic.price ?? ""}球币".changeUnit,
                                    decoration: TextDecoration.lineThrough,
                                    fontSize: 12,
                                    color: Colours.grey99,
                                    height: 1.4,
                                  ).paddingOnly(left: 4),
                              ],
                            ),
                            if (logic.check?.endTime.hasValue == true)
                              QsText(
                                "到期时间：${DateTime.parse(logic.check!.endTime!).formatedString("yyyy-MM-dd")}",
                                fontSize: 10,
                                color: Colours.grey99,
                              )
                          ],
                        ),
                      const Spacer(),
                      GestureDetector(
                        onTap: () => User.needLogin(() {
                          Utils.onEvent("news_open");
                          Get.toNamed(Routes.secretPay,
                              parameters: {"roomId": "${logic.roomId ?? ""}"});
                        }),
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 4),
                          child: Container(
                              height: 40,
                              width: 108,
                              alignment: Alignment.center,
                              clipBehavior: Clip.antiAlias,
                              decoration: BoxDecoration(
                                  color: Colours.main,
                                  borderRadius: BorderRadius.circular(20)),
                              child: QsText(
                                logic.check?.isOpen != 1 ? "立即开通" : "立即续费",
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                              )),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget list() {
    return Stack(
      children: [
        EasyRefresh.builder(
          controller: logic.refreshController,
          scrollController: logic.refreshScroll,
          onRefresh: logic.getRefresh,
          onLoad: logic.loadMore,
          footer: Styles.refreshFooter(position: IndicatorPosition.locator),
          childBuilder: (BuildContext context, ScrollPhysics physics) =>
              ExtendedTabBarView(
                  controller: logic.tabController,
                  children: List.generate(
                      logic.secrets.length,
                      (index) => CustomScrollView(
                              physics: physics,
                              controller: logic.refreshScroll,
                              slivers: [
                                LoadingWidget<bool>(
                                  isLoading: logic.secrets[index] == null,
                                  loading: const SliverToBoxAdapter(),
                                  data: logic.secrets[index]?.length == 0,
                                  noData: const NoDataWidget.sliver(),
                                  child: () => SliverList.list(
                                      children: List.generate(
                                          logic.secrets[index]?.length ?? 0,
                                          (i) {
                                    var e = logic.secrets[index]![i];
                                    if (DateTime.parse(e.freeTime!)
                                        .isBefore(DateTime.now())) {
                                      logic.findHistory ??= i;
                                    }
                                    return SecretItem(
                                      secret: e,
                                      showHistory: i == logic.findHistory,
                                      margin:
                                          const EdgeInsets.fromLTRB(8, 8, 8, 0),
                                      onChange: (change) {
                                        if (change == true) logic.getRefresh();
                                      },
                                    );
                                  })),
                                ),
                                const FooterLocator.sliver()
                              ]))),
        ),
        Positioned(
          bottom: 0,
          left: 0,
          right: 0,
          child: _buyBottom(),
        )
      ],
    );
  }
}
